<template>
  <div v-loading="loading" :element-loading-text="$t('正在生成word文档, 请稍等...')" element-loading-spinner="el-icon-loading">
    <!--    &lt;!&ndash; 进度条 &ndash;&gt;-->
    <!--    <el-progress-->
    <!--      v-show="loading"-->
    <!--      :text-inside="loading"-->
    <!--      :stroke-width="24"-->
    <!--      :percentage="loadingText"-->
    <!--      status="success"-->
    <!--      style="position: sticky; z-index: 2001;padding-top: 10%;"-->
    <!--    />-->
    <el-form ref="form" v-loading="dataLoading" :model="form" :rules="rules" class="dataForm">
      <!-- 动态参数  -->
      <div v-if="mapObject && mapObject !== null && mapObject.length > 0">
        <el-form-item v-for="(item,index) in mapObject" :key="index" :rules="[{ required: true, message: $t('必填字段') }]">
          <div v-if="item.isShow === 'true' || isShowParamNull">
            <span slot="label">
              <span style="color: red; font-size: 16px;">*</span>
              <span>{{ $t(item.label) }}</span>
            </span>
            <div><el-input v-if="item.format === 'text'" v-model="item.param" style="width: 100%" :placeholder="$t('请输入')" @change="repeatAutoFill(item.param, item.templateLabel)" /></div>
            <div><Money v-if="item.format === 'money'" v-model="item.param" style="width: 100%" :placeholder="$t('请输入')" @change="repeatAutoFill(item.param, item.templateLabel)" /></div>
            <div><DatePicker v-if="item.format.includes('date')" v-model="item.param" style="width: 100%" :type="item.format" :placeholder="$t('请选择')" @change="repeatAutoFill(item.param, item.templateLabel)" /></div>
            <div><UserSelect v-if="item.format === 'user'" v-model="item.param" style="width: 100%" :placeholder="$t('请选择')" @change="repeatAutoFill(item.param, item.templateLabel)" /></div>
            <div>
              <el-select
                v-if="item.format === 'ZB'"
                v-model="item.param"
                clearable
                :placeholder="$t('请选择')"
                style="width: 100%"
                @change="repeatAutoFill(item.param, item.templateLabel)"
              >
                <el-option
                  v-for="result in queryResultObject[item.id]"
                  :key="result.value"
                  :label="$t(result.label)"
                  :value="result.value"
                />
              </el-select>
            </div>
          </div>
        </el-form-item>
      </div>
      <div v-else>
        <el-empty :description="$t('无查询条件, 请点击下方生成按钮!')" />
      </div>
      <div v-if="customParams && customParams !== null && customParams.length > 0">
        <div class="area-header mt-15">
          <span class="area-header-title">{{ $t('自定义参数') }}</span>
        </div>
        <el-form-item v-for="(item,index) in customParams" :key="index" :rules="[{ required: true, message: $t('必填字段') }]">
          <div>
            <span slot="label">
              <span style="color: red; font-size: 16px;">*</span>
              <span>{{ $t(item.label) }}</span>
            </span>
            <div>
              <div><el-input v-if="item.format === 'text'" v-model="item.param" style="width: 100%" :placeholder="$t('请输入')" /></div>
              <div><Money v-if="item.format === 'money'" v-model="item.param" style="width: 100%" :placeholder="$t('请输入')" /></div>
              <div><DatePicker v-if="item.format.includes('date')" v-model="item.param" style="width: 100%" :type="item.format" :placeholder="$t('请选择')" /></div>
              <div><UserSelect v-if="item.format === 'user'" v-model="item.param" style="width: 100%" :placeholder="$t('请选择')" /></div>
              <div>
                <el-select
                  v-if="item.format === 'ZB'"
                  v-model="item.param"
                  clearable
                  :placeholder="$t('请选择')"
                  style="width: 100%"
                >
                  <el-option
                    v-for="result in queryResultObject[item.id]"
                    :key="result.value"
                    :label="$t(result.label)"
                    :value="result.value"
                  />
                </el-select>
              </div>
            </div>
          </div>
        </el-form-item>
      </div>
    </el-form>
    <div v-show="!dataLoading" slot="footer" class="dialog-footer" style="text-align: right;">
      <!--保存 取消按钮-->
      <el-switch
        v-if="isShowSwitchParam"
        v-model="isShowParamNull"
        active-color="#13ce66"
        inactive-color="#ff4949"
        :inactive-text="$t('展示所有参数')"
        @click="isShowParamNull = !isShowParamNull"
      />
      <save-btn has-permi="system:word" save-btn-name="生成" />
    </div>
  </div>
</template>

<script>
import { getResultByParamId } from '@/api/system/word/keyword/wordOnlineKeyWord'
  import { downLoadFile } from '@/utils/zipdownload.js'
  import {
    getTemplateKeyWord
  } from '@/api/system/word/template/wordOnlineTemplate.js'
  export default {
    components: {
    },
    data() {
      return {
        // 表单参数
        form: {},
        // 遮罩层
        loading: false,
        dataLoading: false,
        // 表单校验
        rules: {},
        typeOption: [],
        loadingText: 0,
        mapObject: undefined,
        // 是否显示未填写的参数
        isShowParamNull: false,
        // 是否展示参数显示开关
        isShowSwitchParam: true,
        defaultFormat: ['deal', 'spv', 'fund', 'manager', 'lpInvestor', 'hhqy'],
        templatePackagePathArr: [],
        templatePackagePathSendCount: 0,
        queryResultObject: {},
        customParams: {}
      }
    },
    created() {
      this.getDicts('wf_bus_flow_type').then(response => {
        this.typeOption = response.data
      })
    },
    methods: {
      // 初始化数据
      init(data) {
        this.mapObject = undefined
        this.isShowSwitchParam = true
        this.dataLoading = true
        this.form.fileId = data.fileId
        this.form.id = data.id
        this.queryResultObject = {}
        // 提取这个模板下的关键字
        getTemplateKeyWord(this.form.fileId, this.form.id).then(response => {
          console.log('模板下的关键字', response.data)
          this.mapObject = response.data
          if (response.datas) {
            // 自定义参数
            this.customParams = response.datas.customMap
          }

          if (this.mapObject) {
            var tempKeyWord = []
            // 目的是让每种类型的输入框只展示一个.
            this.mapObject.forEach(async item => {
              if (!tempKeyWord.includes(item.templateLabel)) {
                tempKeyWord.push(item.templateLabel)
                item.isShow = 'true'
              } else {
                item.isShow = 'false'
              }
              // 如果是指标 先去查询下拉选项
              if (item.format === 'ZB') {
                await this.getQueryResult(item.id)
              }
              this.$forceUpdate()
            })
          }
          this.dataLoading = false
        })
      },
      /** 重复参数自动补充 **/
      repeatAutoFill(param, templateLabel) {
        console.log(param, templateLabel)
        if (this.mapObject) {
          this.mapObject.forEach(item => {
            if (item.templateLabel === templateLabel && (item.param === undefined || item.param === '' || item.param === null)) {
              item.param = param
            }
          })
        }
      },
      // 表单重置
      reset() {
        this.form = {
          id: undefined,
          fileId: undefined,
          type: undefined,
          remark: undefined,
          createBy: undefined,
          createTime: undefined,
          updateBy: undefined,
          updateTime: undefined,
          delFlag: undefined
        }
        this.resetForm('form')
      },
      // 取消按钮
      cancel() {
        this.$emit('templateFormCancel', undefined)
        this.$parent.$parent.formOpen = false
        this.$parent.$parent.reset()
      },
      // 关闭form页面
      closeForm() {
        // 关闭form页面遮罩层
        this.loading = false
        // 关闭form页面
        if (this.$parent.$parent.formOpen !== undefined) {
          this.$parent.$parent.formOpen = false
        }
        // 刷新list页面
        if (this.$parent.$parent.getList !== undefined) {
          this.$parent.$parent.getList()
        }
      },
      /** 提交按钮 */
      submitForm: function(callBack) {
        return new Promise((resolve, reject) => {
          this.$refs['form'].validate(valid => {
            if (valid) {
              var flag = false
              var param = ''
              var customParam = ''
              console.log('param')
              this.mapObject.forEach(item => {
                if (!item.param) {
                  flag = true
                }
                param += item.value + '@' + item.param + '*'
              })
              this.customParams.forEach(item => {
                if (!item.param) {
                  flag = true
                }
                customParam += item.value + '@' + item.param + '*'
              })
              console.log(this.form.fileId + '&param=' + param)
              if (flag) {
                this.msgError(this.$t('请输入必填项'))
              } else {
                console.log('callback类型: ', callBack)
                // if (callBack !== undefined) {
                //   generateWord(this.form.fileId, param, customParam).then(response => {
                //     this.downloadCloseLoading()
                //     callBack(response.data)
                //     resolve(response.data)
                //   })
                // } else {
                // }
                downLoadFile('/word/wordOnlineTemplate/downloadWord?id=' + this.form.fileId + '&param=' + param + '&customParam=' + customParam, this)
                resolve()
              }
            } else {
              this.locationError(document)
              reject()
            }
          })
        })
      },
      /** 调用方法1: downloadOpenLoading  显示进度条 */
      downloadOpenLoading() {
        this.loading = true
        this.loadingText = 0
      },
      /** 调用方法2: downloadProgress     刷新进度 */
      downloadProgress(percentage) {
        var percentageInt = parseInt(percentage)
        try {
          if (this.loadingText < 30) {
            this.interval = setInterval(this.checkTime, 1000)
          } else {
            if (percentageInt <= this.loadingText) {
              console.log('main ' + percentageInt)
            } else {
              this.loadingText = percentageInt
            }
            clearInterval(this.interval)
            this.interval = undefined
          }
        } catch (e) {
          console.log(e)
          clearInterval(this.interval)
          this.interval = undefined
        }
      },
      /** 调用方法3: downloadCloseLoading 关闭遮盖层 */
      downloadCloseLoading() {
        this.loadingText = 100
        setTimeout(() => {
          this.loading = false
          // 关闭当前窗口
          this.cancel()
        }, 1000)
      },
      checkTime() {
        if (this.loadingText < 30) {
          setTimeout(() => {
            var temp = parseInt(this.loadingText) + (parseInt(Math.random() * 2, 10))
            if (this.loadingText < 30) {
              this.loadingText = temp
            }
            console.log('checkTime' + this.loadingText)
          }, parseInt(Math.random() * (1000 - 500 + 1) + 500, 10))
        } else {
          clearInterval(this.interval)
          this.interval = undefined
        }
      },
      async getQueryResult(id) {
        this.queryResultObject[id] = await this.getResultByParamInfo(id)
      },
      getResultByParamInfo(id) {
        // eslint-disable-next-line no-unused-vars
        return new Promise((resolve, reject) => {
          getResultByParamId(id).then((response) => {
            resolve(response.data.result)
          })
        })
      }
    }
  }
</script>
<style scoped>
.el-select {
  display: inline-block;
  position: relative;
  width: 100%;
}
.dataForm .el-col-12 .el-form-item, .dataForm .el-form-item {
  margin-bottom: 0px !important;
}
</style>
